package com.putong35.common.account.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import com.putong35.common.BuildConfig;
import com.putong35.common.account.AccountManager;
import com.putong35.common.account.data.http.AccountApiHelper;
import com.putong35.common.app.data.HttpCommonApiHelper;
import com.putong35.common.baseactfrag.CompState;
import com.putong35.common.baseactfrag.activity.BaseActivity;
import com.putong35.common.databinding.ActivityForgetPasswordBinding;
import com.putong35.common.utils.EasyToast;
import com.putong35.common.utils.RegularUtils;
import com.putong35.common.utils.ui.EditTextHelper;

public class ForgetPasswordActivity extends BaseActivity {

    public static final String TAG = ForgetPasswordActivity.class.getSimpleName();

    public static void start(Context context) {
        Intent starter = new Intent(context, ForgetPasswordActivity.class);
        context.startActivity(starter);
    }

    /**
     * 通话倒计时90s
     */
    private CountDownTimer mCountDownTimer = new CountDownTimer(60 * 1000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            binding.btnSendCaptcha.setEnabled(false);
            binding.btnSendCaptcha.setText(String.valueOf((millisUntilFinished / 1000) + "s"));
        }

        @Override
        public void onFinish() {
            binding.btnSendCaptcha.setEnabled(true);
            binding.btnSendCaptcha.setText("发送验证码");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle("忘记密码");
        enableBackButton();
        EditTextHelper.setToPhoneType(binding.etAccountID);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    ActivityForgetPasswordBinding binding;
    @Override
    public View createDataView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = ActivityForgetPasswordBinding.inflate(inflater);
        binding.setViewModel(this);
        EditTextHelper.setToPhoneType(binding.etAccountID, 11);
        setEditTextWatcher(binding.etAccountID);
        setEditTextWatcher(binding.etCaptcha);
        setEditTextWatcher(binding.etPwd1);
        setEditTextWatcher(binding.etPwd2);
        
        if (BuildConfig.DEBUG) {
            binding.etAccountID.setText("15959234090");
            binding.etPwd1.setText("111112");
            binding.etPwd2.setText("111112");
            binding.etCaptcha.setText("0000");
        }
        return binding.getRoot();
    }


    private void setEditTextWatcher(EditText et) {
        et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override

            public void afterTextChanged(Editable editable) {
                String accountId = binding.etAccountID.getText().toString().trim();
                String pwd1 = binding.etPwd1.getText().toString().trim();
                String pwd2 = binding.etPwd2.getText().toString().trim();
                String captcha = binding.etCaptcha.getText().toString().trim();

                if (!TextUtils.isEmpty(accountId)
                        && !TextUtils.isEmpty(pwd1)
                        && !TextUtils.isEmpty(pwd2)
                        && !TextUtils.isEmpty(captcha)) {
                    binding.btnAlterPwd.setEnabled(true);
                } else {
                    binding.btnAlterPwd.setEnabled(false);
                }
            }
        });
    }


    public void checkAndReqChangePwd() {
        String inputMobile = binding.etAccountID.getText().toString();
        String pwd1 = binding.etPwd1.getText().toString().trim();
        String pwd2 = binding.etPwd2.getText().toString().trim();
        String captcha = binding.etCaptcha.getText().toString();

        if(TextUtils.isEmpty(inputMobile)) {
            EasyToast.showToast(this, "手机号码不能为空");
            return;
        }

        if(!RegularUtils.isMobileSimple(inputMobile)) {
            EasyToast.showToast(this, "请输入有效的手机号");
            return;
        }

        if(TextUtils.isEmpty(pwd1)) {
            EasyToast.showToast(this, "密码不能为空");
            return;
        } else if (pwd1.length() > 20 || pwd1.length() < 6) {
            EasyToast.showToast(this, "请输入6-20位的密码");
            return;
        }

        if(TextUtils.isEmpty(pwd2)) {
            EasyToast.showToast(this, "密码不能为空");
            return;
        } else if (pwd2.length() > 20 || pwd2.length() < 6) {
            EasyToast.showToast(this, "请输入6-20位的密码");
            return;
        }

        if (!TextUtils.equals(pwd1, pwd2)) {
            EasyToast.showToast(this, "两次输入的密码不一致");
            return;
        }

        if(TextUtils.isEmpty(captcha)) {
            EasyToast.showToast(this, "验证码不能为空");
            return;
        } else if (captcha.length() < 4) {
            EasyToast.showToast(this, "请输入有效的4位验证码");
            return;
        }


        setState(CompState.EMPTY_REFRESHING);
        AccountApiHelper.changePwd(inputMobile, pwd1, captcha, (code, msg, data, extObj) -> {
            Log.d(TAG, "onSuccess: " + data);
            setState(CompState.DATA);
            AccountManager.getInstance().clear();
            EasyToast.showToast(ForgetPasswordActivity.this, "修改成功，请重新登录");
            setResult(RESULT_OK);
            finish();

        }, (errCode, msg) -> {
            Log.d(TAG, "onFailure: " + msg);
            setState(CompState.DATA);
        });


        /*
        UrlParams urlParams = new UrlParams();
        urlParams.put("mobile", inputMobile);
        urlParams.put("code", captcha);

        setState(CompState.EMPTY_REFRESHING);
        Observable.create(new ObservableOnSubscribe<Object>() {
            @Override
            public void subscribe(ObservableEmitter<Object> e) throws Exception {
                Thread.sleep(1000);
                e.onComplete();
            }
        }).observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.newThread())
                .subscribe(new Observer<Object>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        Log.e("pww", "reqUserInfo onSubscribe: ");
                    }

                    @Override
                    public void onNext(Object value) {
                        Log.e("pww", "reqUserInfo onNext: ");
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("pww", "reqUserInfo onError: ");
                        e.printStackTrace();
                        setState(CompState.DATA);
                    }

                    @Override
                    public void onComplete() {
                        setState(CompState.DATA);
                        EasyToast.showToast(ForgetPasswordActivity.this, "密码修改成功，请重新登录！");
                        finish();
                    }
                });
*/
    }


    public void reqCaptcha() {
        String inputMobile = binding.etAccountID.getText().toString();
        if(TextUtils.isEmpty(inputMobile)) {
            EasyToast.showToast(this, "手机号码不能为空");
            return;
        }

        if(!RegularUtils.isMobileSimple(inputMobile)) {
            EasyToast.showToast(this, "请输入有效的手机号");
            return;
        }

        setState(CompState.EMPTY_REFRESHING);
        HttpCommonApiHelper.getSmsCode(AccountApiHelper.SMS_TYPE_REGISTER, inputMobile, (code, msg, data, extObj) -> {
            Log.d(TAG, "onSuccess: " + data);
            EasyToast.showToast(ForgetPasswordActivity.this, "验证码已发送！");
            setState(CompState.DATA);

        }, (errCode, msg) -> {
            Log.d(TAG, "onFailure: " + msg);
            setState(CompState.DATA);
        });

        mCountDownTimer.start();
    }

}
